import { useEffect, useState } from 'react'
import './index.scss'
import { useNavigate } from 'react-router-dom'
import { SearchBar, Button, List } from 'antd-mobile'
import { ArrowLeftOutlined } from '@ant-design/icons'
import axios from '../../api/index'
import dayjs from 'dayjs'

type SearchResult = {
  sickCircleId: number
  title: string
  detail: string
  amount: number
  collectionNum: number
  commentNum: number
  releaseTime: number
}

function Byqss() {
  const navigate = useNavigate()
  const [keyword, setKeyword] = useState('')
  const [searchHistory, setSearchHistory] = useState<string[]>([])
  const [searchResults, setSearchResults] = useState<SearchResult[]>([])
  const [isSearching, setIsSearching] = useState(false)

  // 从localStorage加载搜索历史
  useEffect(() => {
    const savedHistory = localStorage.getItem('byqssSearchHistory')
    if (savedHistory) {
      setSearchHistory(JSON.parse(savedHistory))
    }
  }, [])

  // 保存搜索历史到localStorage
  const saveSearchHistory = (keyword: string) => {
    if (!keyword.trim()) return
    
    const newHistory = [keyword, ...searchHistory.filter(item => item !== keyword)].slice(0, 10)
    setSearchHistory(newHistory)
    localStorage.setItem('byqssSearchHistory', JSON.stringify(newHistory))
  }

  // 搜索功能
  const handleSearch = async (keyword: string) => {
    if (!keyword.trim()) return
    
    // 保存搜索历史
    saveSearchHistory(keyword)
    setIsSearching(true)
    
    try {
      const response = await axios.get('/user/sickCircle/v1/searchSickCircle', {
        params: {
          keyWord: keyword
        }
      })
      console.log('搜索结果:', response.data)
      setSearchResults(response.data.result || [])
    } catch (error) {
      console.error('搜索失败:', error)
      setSearchResults([])
    } finally {
      setIsSearching(false)
    }
  }

  // 清除搜索内容并恢复默认状态
  const handleClear = () => {
    setKeyword('')
    setSearchResults([])
    setIsSearching(false)
  }

  return (
    <div className='byqss'>
      {/* 搜索头部 */}
      <div className='byqss-header'>
        <div className='search-container'>
          <div className='back-btn' onClick={() => navigate(-1)}>
            <ArrowLeftOutlined />
          </div>
          <div className='search-input'>
            <SearchBar 
              value={keyword} 
              onChange={setKeyword} 
              onSearch={() => handleSearch(keyword)} 
              onClear={handleClear}
              placeholder='请输入病症名称或标题关键词' 
              showCancelButton={false}
            />
          </div>
          <Button color='primary' size='small' onClick={() => handleSearch(keyword)}>搜索</Button>
        </div>
      </div>

      {/* 搜索历史 */}
      {searchHistory.length > 0 && !isSearching && searchResults.length === 0 && (
        <div className='byqss-history-container'>
          <div className='byqss-history-header'>
            <span>搜索历史</span>
            <Button size='mini' fill='none' onClick={() => {
              setSearchHistory([])
              localStorage.removeItem('byqssSearchHistory')
            }}>清空</Button>
          </div>
          <div className='byqss-history-content'>
            {searchHistory.map((item, index) => (
              <span 
                key={index} 
                className='byqss-history-item'
                onClick={() => {
                  setKeyword(item)
                  handleSearch(item)
                }}
              >
                {item}
              </span>
            ))}
          </div>
        </div>
      )}

      {/* 搜索结果 */}
      {searchResults.length > 0 && (
        <div className='byqss-results'>
          <List header={`搜索结果 (${searchResults.length}条)`}>
            {searchResults.map((item, index) => (
              <List.Item 
                key={index} 
                onClick={() => navigate(`/byqxq/${item.sickCircleId}`)}
                className='result-item'
              >
                <div className='result-content'>
                  <div className='result-title'>{item.title}</div>
                  <div className='result-detail'>{item.detail}</div>
                  <div className='result-meta'>
                    <span className='time'>{dayjs(item.releaseTime).format('YYYY-MM-DD HH:mm:ss')}</span>
                    <span className='stats'>
                      <span>收藏 {item.collectionNum}</span>
                      <span>评论 {item.commentNum}</span>
                      {item.amount > 0 && <span>悬赏 {item.amount}</span>}
                    </span>
                  </div>
                </div>
              </List.Item>
            ))}
          </List>
        </div>
      )}

      {/* 无结果提示 */}
      {isSearching && (
        <div className='byqss-loading'>
          <div>搜索中...</div>
        </div>
      )}

      {!isSearching && searchResults.length === 0 && searchHistory.length === 0 && (
        <div className='byqss-empty'>
          <div>请输入关键词进行搜索</div>
        </div>
      )}

      {!isSearching && searchResults.length === 0 && searchHistory.length > 0 && (
        <div className='byqss-empty'>
          <div>暂无搜索结果</div>
        </div>
      )}
    </div>
  )
}

export default Byqss